package com.doit.dophin.utils

import scala.collection.mutable.ListBuffer

/**
 * @DATE 2022/4/1/23:49
 * @Author MDK
 * @Version 2021.2.2
 *
 * 写一个树节点的练习测试
 * a页面可以到达bcd页面
 * c页面可以到达ef页面
 * f页面可以到达xy页面
 * d页面可以到达gh页面
 *
 * a-->b
 * a-->c-->e
 *     c-->f
 *         f-->x
 *         f-->y
 * a-->d-->g
 *     d-->h
 * */

case class TreeNode(url:String, children:List[TreeNode])

object FollowerPv {
  def main(args: Array[String]): Unit = {

    //构建树节点
    val x = TreeNode("x",null)
    val y = TreeNode("y",null)
    val f = TreeNode("f",List(x,y))

    val g = TreeNode("g",null)
    val h = TreeNode("h",null)
    val d = TreeNode("d",List(g,h))

    val e = TreeNode("e",null)

    val c = TreeNode("c",List(e,f))
    val b = TreeNode("b",null)
    val a = TreeNode("a",List(b,c,d))

    val buffer = new ListBuffer[(TreeNode, Int)]
    findNodeFollowerPv2(a,buffer)
    println(buffer.map(tp=>(tp._1.url,tp._2)))

  }

  //写方法
  def findNodeFollowerPv(node: TreeNode):Int={

    var followerPv = 0
    val childern: List[TreeNode] = node.children

    if(childern!=null){
      followerPv += childern.size
      //递归调用方法,如果有子节点,则递归调用方法直至没有子节点,将计算出来的值与之前的值求和
      for (child <- childern) {
        followerPv += findNodeFollowerPv(child)
      }
    }
    followerPv
  }

  //让本方法自行调用
  def findNodeFollowerPv2(node: TreeNode,buf:ListBuffer[(TreeNode,Int)]):Int={

    var followerPv = 0
    val childern: List[TreeNode] = node.children

    if(childern!=null){
      followerPv += childern.size
      //递归调用方法,如果有子节点,则递归调用方法直至没有子节点,将计算出来的值与之前的值求和
      for (child <- childern) {
        followerPv += findNodeFollowerPv2(child,buf)
      }
    }
    buf += ((node,followerPv))
    followerPv
  }

}
